package server.servlets;


import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import commons.Manager;
import commons.Media;
import commons.User;
import commons.exceptions.PasswordException;
import server.filters.RestrictedPagesToConnectedUser;

/**
 * Servlet used to obtain media_list, admin_list, guest_list and is_playing in AJAX
 * @author Romain Pellerin
 */
public class Poll extends HttpServlet {

	private static final long serialVersionUID = 8021927605804737942L;

	private final static String IS_USER_CONNECTED	= "is_user_connected";
	private final static String IS_ADMIN			= "is_admin";
	private final static String MEDIA_LIST			= "media_list";
	private final static String ADMIN_LIST			= "admin_list";
	private final static String GUEST_LIST			= "guest_list";
	private final static String IS_PLAYING			= "is_playing";
	private final static String GUEST_PWD			= "guest_password";

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");

		User user;
		
		Map<String,Object> json_string = new LinkedHashMap<String,Object>();
		
		if ((user = RestrictedPagesToConnectedUser.getUserIfConnected(request)) != null) {
			boolean is_user_admin = user.isAdmin();
			List<Media> media_list = Manager.getInstance().getMediaList().getArrayList();
			List<User> admin_list = Manager.getInstance().getAdminArrayList();
			List<User> guest_list = Manager.getInstance().getGuestArrayList();
			boolean is_playing = Manager.getInstance().isPlaying();
			String guest_password;
			try {
				guest_password = User.getGuestPassword();
			} catch (PasswordException e) {
				guest_password = e.getMessage();
			}
			json_string.put(IS_ADMIN,is_user_admin);
			json_string.put(MEDIA_LIST, media_list);
			json_string.put(ADMIN_LIST, admin_list);
			json_string.put(GUEST_LIST, guest_list);
			json_string.put(IS_PLAYING, is_playing);
			json_string.put(GUEST_PWD, guest_password);
			json_string.put(IS_USER_CONNECTED, true);
		}
		else {
			json_string.put(IS_USER_CONNECTED, false);
		}
		response.getWriter().write(new Gson().toJson(json_string));
	}
}
